package top.yuyufeng.web.mobileServlet;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;

/**
 * @author yuyufeng
 * @date 2018/1/22
 */
@WebServlet(name = "DoValidServletMB", urlPatterns = "/doValidServletMB")
public class DoValidServletMB extends HttpServlet {
    private static int ALLOWANCE = 5;  //容错 10px 以内都算通过


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
        JSONObject jsonResult = new JSONObject();

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        HttpSession session = req.getSession();
        String location = req.getParameter("location");


        int x = Integer.valueOf(location.split(",")[0]);
        int y = Integer.valueOf(location.split(",")[1]);


        System.out.println(location);
        Map<String, String> map = (Map<String, String>) session.getAttribute("validMap");

        if (map == null) {
            jsonResult.put("status", 501);
            jsonResult.put("data", "验证失败");
            Writer writer = response.getWriter();
            writer.write(jsonResult.toString());
            writer.flush();
            return;
        }

        String sessionMapLocation = map.get("location");

        int sx = Integer.valueOf(sessionMapLocation.split(",")[0]);
        int sy = Integer.valueOf(sessionMapLocation.split(",")[1]);




        if (Math.abs(sx - x) < ALLOWANCE && Math.abs(sy - y) < ALLOWANCE) {
            jsonResult.put("status", 200);
            jsonResult.put("data", "验证通过");

        } else {
            jsonResult.put("status", 500);
            jsonResult.put("data", "验证失败");
        }

        Writer writer = response.getWriter();
        writer.write(jsonResult.toString());
        writer.flush();

    }
}
